<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加分类 -->
      <el-row>
        <el-col
          ><el-button type="primary" @click="showAddCateDialog()"
            >添加分类</el-button
          ></el-col
        >
      </el-row>

      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
        class="treeTable"
      >
        <!-- 是否有效列 -->
        <template slot="isok" scope="scope">
          <i
            v-if="scope.row.cat_deleted === false"
            class="el-icon-success"
            style="color: lightgreen"
          ></i>
          <i v-else class="el-icon-error" style="color: red"></i>
        </template>
        <!-- 排序列 -->
        <template slot="order" scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCateById(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- *********************************对话框*************************** -->
    <!-- 添加分类 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed()"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
            <!-- options用来指定数据源 -->
            <!-- props用来指定配置对象 -->
            <el-cascader
                v-model="selectedKeys"
                :options="parentCateList"
                :props="{
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                    checkStrictly: 'true'
                    }"
                @change="parentCateChanged"
                clearable
            >
            </el-cascader>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改分类 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed()"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="分类名" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate()">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      //商品分类的数据列表
      cateList: [],
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //总数据条数
      total: 0,
      //为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //表示将当前列定义为模板列
          type: "template",
          //表示当前这一列使用的模板名称
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      //添加分类的表单数据对象
      addForm: {
        cat_name: "", //   分类名称
        cat_pid: 0, //父级分类id 默认无父级
        cat_level: 0, //分类等级，默认一级
      },
      //添加分类表单的验证规则对象
      addFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级分类的数据列表
      parentCateList: [],
      //选中的父级分类的Id数组
      selectedKeys: [],
      //控制编辑商品分类对话框的显示隐藏
      editDialogVisible: false,
      //编辑分类的表单
      editForm:{
          cat_name: '',
          id:0
      },
      //编辑分类表单的验证规则
      editFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名", trigger: "blur" },
        ]
      }

    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取所有的商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类数据失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum;
      this.getCateList();
    },
    //点击展示添加分类的对话框
    showAddCateDialog() {
      //先获取父级分类的数据列表
      this.getParentCateList();
      //展示对话框
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类数据失败");
      this.parentCateList = res.data;
    },
    //选择项发生变化，触发这个函数
    parentCateChanged(){
        //如果selectedKeys数组的length>0 ,证明选中了父级分类
        if(this.selectedKeys.length > 0){
            //父级分类的id
            this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length-1]
            //为当前分类等级赋值
            this.addForm.cat_level = this.selectedKeys.length
            return
        }else{
            this.addForm.cat_pid = 0
            this.addForm.cat_level = 0
        }
    },
    //点击添加分类
    async addCate(){
        this.$refs.addFormRef.validate(valid=>{
            if(!valid) return
        })
        
        const {data:res} = await this.$http.post('categories',this.addForm);
        if(res.meta.status !== 201) return this.$message.error('添加分类失败');

        this.$message.success("添加分类成功");
        this.getCateList();
        this.addCateDialogVisible = false;
    },
    //监听对话框的关闭事件，重置表单数据
    addCateDialogClosed(){
        this.$refs.addFormRef.resetFields();
        this.selectedKeys = [];
        this.addForm.cat_level = 0;
        this.addForm.cat_pid = 0;
    },
    //监听编辑对话框的关闭
    editDialogClosed(){
        this.$refs.editFormRef.resetFields();
    },
    //展示编辑对话框
    showEditDialog(data){
        this.editDialogVisible = true;
        this.editForm.cat_name = data.cat_name;
        this.editForm.id = data.cat_id;
    },
    //点击发起编辑分类的请求
    async editCate(){
        //校验
        this.$refs.editFormRef.validate(valid=>{
            if(!valid) return;
        })

        //发起请求
        const {data:res} = await this.$http.put(`categories/${this.editForm.id}`,{cat_name: this.editForm.cat_name});
        if(res.meta.status !== 200) return this.$message.error('编辑分类失败');
        this.$message.success('编辑分类成功');
        this.getCateList();
        this.editDialogVisible = false;
    },
    async removeCateById(id) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      ).catch((err) => err);

      //如果用户确认删除，则返回值为'confirm',取消则是'cancel'
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");
      //发起删除请求
      const { data: res } = await this.$http.delete(`categories/${id}`);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      //刷新数据列表，跳回第一页
      this.queryInfo.pagenum = 1;
      this.getCateList();
    },

  },
};
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}

.el-cascader{
    width: 100%;
}

</style>